package com.imgpro.aops;


import com.imgpro.annotation.AutoFill;
import com.imgpro.Constant.AutoFillConstant;
import com.imgpro.Context.BaseContext;
import com.imgpro.Enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;


//自定义切面，用来实现自动填充
@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    @Pointcut("execution(* com.imgpro.mapper.*.*(..)) && @annotation(com.imgpro.annotation.AutoFill)")
    public void autoFillPointCut(){}

    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws Throwable {
        log.info("开始进行自动填充___触发Autofill，当前方法为：{}", joinPoint.getSignature().getName());
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

        AutoFill autoFill = methodSignature.getMethod().getAnnotation(AutoFill.class);

        OperationType operationType = autoFill.value();

        Object[] args = joinPoint.getArgs();
        if(args == null || args.length == 0){
            return;
        }
        Object arg = args[0];

        LocalDateTime nowTime = LocalDateTime.now();

//        log.info("开始进行自动填充___触发了当前自定义aop，当前方法为：{}", methodSignature.getMethod().getName());
        if(operationType == OperationType.INSERT){
            Method setCreateAt = arg.getClass().getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method setUpdateAt = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method stLastLoginAt = arg.getClass().getMethod(AutoFillConstant.SET_LAST_LOGIN_TIME, LocalDateTime.class);

            setCreateAt.invoke(arg, nowTime);
//            setCreateUser.invoke(arg, currentId);

            setUpdateAt.invoke(arg, nowTime);

            stLastLoginAt.invoke(arg, nowTime);
//            setUpdateUser.invoke(arg, currentId);

        }
        else if (operationType == OperationType.UPDATE) {
//            TODO 这里还要修改用户信息修改功能
            Method setUpdateAt = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method stLastLoginAt = arg.getClass().getMethod(AutoFillConstant.SET_LAST_LOGIN_TIME, LocalDateTime.class);

            setUpdateAt.invoke(arg, nowTime);
            stLastLoginAt.invoke(arg, nowTime);
        }
    }
}
